<?php
/*
 * @Author: an
 * @Date: 2021/12/7
 * @Description: 阿里云音视频令牌处理
 */


namespace App\Services\Aliyun\AudioAndVideo;


use App\Services\Aliyun\BaseService;
use App\Services\Configs\DefaultService;

class RtcTokenService extends BaseService
{
    private $appid;
    private $appKey;
    public $gslb;//服务地址
    private $expireTimeInSeconds = 86400;//令牌过期时间

    public function __construct()
    {
        $config = $this->getConfig(DefaultService::ALI_AV);
        $this->appid = $config['appid'];
        $this->appKey = $config['appKey'];
        $this->gslb = $config['gslb'];
    }

    /**
     * 获取音视频令牌
     * @param $channel 频道
     * @param $userId 用户ID
     * @return string
     * @author an
     * @time 2021-12-07 13:03
     */
    public function get($channel, $userId)
    {
        $nonce = 'AK-' . get_uuid();
        $expire_ts = time() + $this->expireTimeInSeconds;
        $str = $this->appid . $this->appKey . $channel . $userId . $nonce . $expire_ts;
        $token = hash("sha256", $str);
        return array(
            'userid' => $userId,// 用户ID
            'channel' => $channel,// 频道
            'timestamp' => $expire_ts,// 时间戳
            'nonce' => $nonce,// 随机码
            'appid' => $this->appid,// 应用ID
            'gslb' => $this->gslb,// gslb服务地址
            'token' => $token // 令牌
        );
    }

    /**
     * 设置过期时间
     * @param $expire_in 多久过期，单位秒
     * @author an
     * @time 2021-12-07 15:41
     */
    public function setExpireTime($expire_in)
    {
        $this->expireTimeInSeconds = $expire_in;
    }

    /**
     * 根据频道加密用户ID
     * @param $channel_id 频道ID
     * @param $user_id 用户ID
     * @return false|string
     * @author an
     * @time 2021-12-07 15:02
     */
    private function createUserID($channel_id, $user_id)
    {
        $s = $channel_id . '/' . $user_id;
        $uid = hash('sha256', $s);
        return substr($uid, 0, 16);
    }
}
